import { useState, forwardRef, useImperativeHandle } from "react";
import { uuid } from "../../util";
import Button from 'antd/es/button';
import Input from 'antd/es/input';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import './index.less';

export interface IInputInfo {
    key: string;
    value?: string;
}

export interface IEditableInputRef {
    getValidValues: () => string[];
}

export interface IEditableInputProps {
    inputProps?: Partial<{
        placeholder: string;
    }>;
    addedBtnProps?: Partial<{
        name: string;
    }>;
    minSize?: number;
    defaultValue?: string[];
}

export const EditableInput = forwardRef<IEditableInputRef, IEditableInputProps>(function EditableInput(props, ref) {
    const { defaultValue = [], minSize = 0, inputProps, addedBtnProps } = props;
    const [inputMap, setInputMap] = useState<Map<string, string | undefined>>(new Map(defaultValue.map(v => [uuid(), v])));

    useImperativeHandle(ref, () => {
        return {
            getValidValues: () => [...inputMap.values()].filter((v): v is string => !!v)
        };
    }, [inputMap]);

    const modifyInputMap = (action: 'add' | 'delete' | 'update', payload: IInputInfo) => {
        setInputMap((prevMap) => {
            const { key, value } = payload;
            const newMap = new Map([...prevMap.entries()]);
            if (action === 'add') {
                newMap.set(key, value);
            } else if (action === 'update') {
                newMap.set(key, value);
            } else if (action === 'delete') {
                if (newMap.size > minSize) {
                    newMap.delete(key)
                }
            }
            return newMap;
        })
    }

    return <>
        {[...inputMap.entries()].map(([key, value]) => <div key={key} className="inline-flex" >
            <Input placeholder={inputProps?.placeholder} value={value} onChange={(event) => modifyInputMap('update', { key: key, value: event.target.value })} size='small' />
            {inputMap.size > minSize && <MinusCircleOutlined onClick={() => modifyInputMap('delete', { key: key })} />}
        </div>
        )}
        <Button
            type="dashed"
            onClick={() => modifyInputMap('add', { key: uuid() })}
            size='small'
            icon={<PlusOutlined />}
        >
            {addedBtnProps?.name}
        </Button>
    </>
})